{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "60c2df40",
   "metadata": {},
   "source": [
    "# 基于Transformer的文本自动摘要\n",
    "\n",
    "本示例演示如何使用HuggingFace Transformers库，调用预训练模型进行中文或英文文本的自动摘要。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c81fc17",
   "metadata": {},
   "source": [
    "## 1. 安装依赖\n",
    "\n",
    "- `pip install transformers torch`"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "122cb2f7",
   "metadata": {},
   "source": [
    "## 2. 加载预训练摘要模型\n",
    "\n",
    "以英文Bart和中文ChatGLM2为例，可根据需求更换模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7a034d6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import pipeline\n",
    "\n",
    "# 英文摘要模型（facebook/bart-large-cnn）\n",
    "summarizer_en = pipeline(\"summarization\", model=\"facebook/bart-large-cnn\")\n",
    "\n",
    "# 中文摘要模型（THUDM/chatglm2-6b）可选，需有显卡和模型权重\n",
    "# summarizer_zh = pipeline(\"summarization\", model=\"THUDM/chatglm2-6b\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b5a92df",
   "metadata": {},
   "source": [
    "## 3. 输入文本并生成摘要\n",
    "\n",
    "可替换为任意英文或中文长文本。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4fd2ee6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例英文长文本\n",
    "text_en = \"\"\"\n",
    "The Transformer architecture has revolutionized natural language processing by enabling models to capture long-range dependencies and context. It forms the backbone of state-of-the-art models such as BERT, GPT, and T5. Summarization is a key application, where the model condenses long documents into concise summaries while preserving core information.\n",
    "\"\"\"\n",
    "\n",
    "summary_en = summarizer_en(text_en, max_length=60, min_length=20, do_sample=False)[0]['summary_text']\n",
    "print(\"英文摘要：\", summary_en)\n",
    "\n",
    "# 示例中文长文本（如需中文摘要模型）\n",
    "# text_zh = \"Transformer架构极大推动了自然语言处理的发展，能够捕捉长距离依赖和上下文信息。它是BERT、GPT、T5等主流模型的基础。文本摘要是重要应用之一，模型需在保留核心信息的同时将长文压缩为简明摘要。\"\n",
    "# summary_zh = summarizer_zh(text_zh, max_length=60, min_length=20, do_sample=False)[0]['summary_text']\n",
    "# print(\"中文摘要：\", summary_zh)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
